package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"server-admin-api/message"
	"server-admin-api/service"
	"server-admin-api/views"
	"strconv"
)

type GroupApi struct {
	service *service.GroupService
}

func NewGroupApi() *GroupApi {
	return &GroupApi{
		service: service.NewGroupService(),
	}
}

// Create 创建
func (g *GroupApi) Create(c *gin.Context) {
	var data views.GroupCreate
	c.DefaultQuery("id", "0")
	id, _ := strconv.Atoi(c.Query("id"))
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError(err.Error()))
		return
	}
	if err := g.service.CreateGroup(uint(id), data); err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError("创建服务分组失败"))
		return
	}
	c.JSON(http.StatusOK, message.NewResultMsg().Success("创建服务分组成功"))
	return
}

// Pages 分页
func (g *GroupApi) Pages(c *gin.Context) {
	c.DefaultQuery("page", "1")
	c.DefaultQuery("size", "10")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	title := c.Query("title")
	pages, err := g.service.GroupPage(page, size, title)
	if err != nil {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError(err.Error()))
		return
	}
	c.JSON(http.StatusOK, message.NewResultMsg().Success(pages))
	return
}

// Delete 删除
func (g *GroupApi) Delete(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	if id == 0 {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError("参数丢失"))
		return
	}
	if g.service.DeleteById(uint(id)) {
		c.JSON(http.StatusBadRequest, message.NewResultMsg().ParamError("删除数据失败"))
		return
	}
	c.JSON(http.StatusOK, message.NewResultMsg().Success("删除数据成功"))
	return
}